package com.thread.callable;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Test {

	public static void main(String[] args) {
		ExecutorService exec = Executors.newCachedThreadPool();
		ArrayList<Future<String>> results = new ArrayList<Future<String>>();

		for (int i = 0; i < 10; i++) {
			// 必须通过ExecutorService的submit方法调用，该方法产生Future对象
			results.add(exec.submit(new TaskWithResult(i)));
		}

		for (Future<String> fs : results) {
			try {
				// Future提供isDone()方法检查是否完成，也可以直接调用get()方法，这时，get()将阻塞，直至结果准备就绪，也可以在调用get()前，调用具有超时的get()或调用isDone()来检查任务是否完成
				System.out.println(fs.get());
			} catch (InterruptedException e) {

			} catch (ExecutionException e) {
				// TODO: handle exception
			} finally {
				exec.shutdown();
			}
		}
	}

}
